package drivers;

import input_output.InboxMonitor;

import java.awt.EventQueue;
import java.io.IOException;
import java.sql.Connection;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

import config.DatabaseConnection;
import config.FlatFileLoaders;

import simulators.MessageGeneratorJFrame;
import simulators.MessageInbox;
import types.TextMessage;


public class TestDriver
{
    // Logger
    private static Logger myLogger = Logger.getLogger(TestDriver.class.getName());
    public static boolean isAlive = true;
    
    public static void main(String args[]) throws SecurityException, IOException
    {
	// Set up logging
	BasicConfigurator.configure();
	
	myLogger.info("TestDriver has started.");
	
	// Connect to the database
	FlatFileLoaders.loadSystemProperties();
	Connection dbc = DatabaseConnection.startDBConnection();
	
	// Start thread to listen for new messages
	InboxMonitor inboxMonitor = new InboxMonitor();
	inboxMonitor.monitor();
	
	// Testing
	testMessages();
	runGUI();
	
	while (isAlive)
	{
	    try
	    {
		Thread.sleep(1000);
	    }
	    catch (InterruptedException e)
	    {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	}
	
	// SHUT DOWN
	
	// Stop threads
	inboxMonitor.stop();
		
	// Close connection to the database
	DatabaseConnection.closeConnection(dbc);
	
    }
    
    private static void testMessages()
    {
	TextMessage tm;
	tm = new TextMessage("9738565234","REgister Brian Goodacre bcg@gmx.ru");
	MessageInbox.addMessage(tm);
	tm = new TextMessage("9738565234","new banana");
	MessageInbox.addMessage(tm);
	tm = new TextMessage("9738565234","banana");
	MessageInbox.addMessage(tm);
	tm = new TextMessage("9008502509","banana");
	MessageInbox.addMessage(tm);
    }

    private static void runGUI()
    {
	// Run Message Generator GUI
	EventQueue.invokeLater(new Runnable()
	{
	    public void run()
	    {
		try
		{
		    MessageGeneratorJFrame frame = new MessageGeneratorJFrame();
		    frame.setVisible(true);
		}
		catch (Exception e)
		{
		    e.printStackTrace();
		}
	    }
	});
	
    }
}
